package org.cainiao.basic.concurrent.juc.executor;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static org.cainiao.util.Util.logLn;

/**
 * <br />
 * <p>
 * Author: Cai Niao(wdhlzd@163.com)<br />
 */
public class ScheduledExecutorServiceTest {

    private static final ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1);

    public static void main(String[] args) throws InterruptedException {
        test1();
    }

    private static void test1() throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            int j = i;
            new Thread(() -> consume(j)).start();
            TimeUnit.SECONDS.sleep(1);
        }
    }

    private static void consume(int i) {
        boolean isEmpty = scheduler.getQueue().isEmpty();
        logLn("consume >>> i = %d, isEmpty = %b", i, isEmpty);
        if (isEmpty) {
            scheduler.schedule(() -> {
                logLn("update start >>> i = %d", i);
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                logLn("update end >>> i = %d", i);
            }, 3, TimeUnit.SECONDS);
        }
    }
}
